﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using BusinessLogic.Interfaces;
using Domain;
using Domain.Entities;

namespace BusinessLogic.Implementations
{
    public class EFProduceInPackageRepository :IProduceInPackageRepository
    {
        private EFDbContext context;
        public EFProduceInPackageRepository(EFDbContext context)
        {
            this.context = context;
        }
        public IEnumerable<ProduceInPackage> GetProduceInPackages()
        {
            return context.ProduceInPackages.ToList();
        }

        public ProduceInPackage GetProduceInPackageById(int id)
        {
            return context.ProduceInPackages.FirstOrDefault(i => i.Id == id);
        }

        public void CreateProduceInPackage(ProduceInPackage package)
        {
            context.ProduceInPackages.Add(package);
            context.SaveChanges();
        }

        public void SaveProduceInPackage(ProduceInPackage package)
        {
            if (package.Id == 0)
            {
                context.ProduceInPackages.Add(package);
            }
            else
            {
                context.Entry(package).State = EntityState.Modified;
            }
            context.SaveChanges();
        }

        public void DeleteProduceInPackageById(int id)
        {
            context.ProduceInPackages.Remove(GetProduceInPackageById(id));
            context.SaveChanges();
        }

        public IEnumerable<Prepackage> GetPrepackagesByProduce(Produce produce)
        {
            return
                GetProduceInPackages()
                    .Where(i => i.ProduceId == produce.Id)
                    .Select(p => p.Prepackage)
                    .OrderBy(i => i.Weight)
                    .GroupBy(i => i.Weight)
                    .Select(i => i.FirstOrDefault())
                    .ToList();
        }
        
    }
}
